<?php
/**
 * 
 *
 * @copyright Copyright (c) 2013
 * @version   1.0
 * 
 * @todo commenter la classe
 **/
class Entity
{	
	public $id; 
	public $code;
	public $name;
	public $bddTable;
	public $desc;
	public $objectId;
	
    /**
    * Constructor
    * 
    * @return void
    */    
    public function __construct () {
		$this->id = 0;
    }
												 
	public function read ($entityCode) {
		DbConnection::getInstance()->Execute(
			'SELECT `id`, `code`, `name`, `bdd_table`, `desc`, `object_id` FROM blog.sys_def_entity where code = <s:code/>', 
			array( 's:code' => $entityCode));
	
		
		if ( $row = DbConnection::getInstance()->nextRow())
		{		
			$i = 0;
			$this->id = $row[$i++]; 
			$this->code = $row[$i++];
			$this->name = $row[$i++];
			$this->bddTable = $row[$i++];
			$this->desc = $row[$i++];
			$this->objectId = $row[$i++];
			return true;
		}
		
		$this->id = 0; 
		return false;
	}

	public function createSysObject ($authorId=0) {
		DbConnection::getInstance()->Execute(
			'insert into sys_object (author, entity_id) values (<n:authorId/>, <n:entityId/>)',
			array ('n:authorId'=>$authorId, 'n:entityId'=>$this->id));
	
		$this->id = DbConnection::getInstance()->getInsertId();		
		return $this->id;
		
	}												 
	public function readFields () {
		DbConnection::getInstance()->Execute(
			'SELECT f.`code`, `name`, description, `comment`, e.`code`, sqlColName FROM sys_def_field  f LEFT OUTER JOIN sys_enum e ON (e.id = f.enum_type) WHERE entity_id = <n:e_id/>', 
			array( 'n:e_id' => $this->id));

		$fields = array();		
		while ( $row = DbConnection::getInstance()->nextRow())
		{		
			$f = new EntityField();
			$i=0;
			$f->code = $row[$i++];
			$f->name = $row[$i++];
			$f->desc = $row[$i++];
			$f->comment = $row[$i++];
			$f->type = $row[$i++];
			$f->sqlColName = $row[$i++];
			$fields[$f->code]=$f;
		}
		
		return $fields;
	}
	
} // END class